//
//  TCSdMenuViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/6/24.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class TCSdMenuViewController: NSViewController {
    var role:OneRole = .join
    var sourceInfo:TRTCScreenCaptureSourceInfo!
    
    var hasCursor:Bool = false
    var hasHighlight:Bool = true
    
    var upMenu:NSMenu?
    
    var kTabWidth = CGFloat(90)
    var isExpand:Bool = true {
        didSet {
            let imageString = isExpand ? "icon_shared_topbuttom":"icon_shared_bottombuttom"
            self.topButtom.iconImage = NSImage.image(name:imageString)
            
            let x = (KSCREENWIDTH - self.view.frame.width)/2
            let y = isExpand ? KSCREENHEIGHT-self.view.frame.height:(KSCREENHEIGHT - 22)
            self.view.window?.setFrameOrigin(CGPoint.init(x: x, y: y))
        }
    }
    
    var pausing:Bool = false {
        didSet {
            let backColor = pausing ? color_rgba(r: 250, g: 170, b: 40):color_green190
            self.container.layer?.backgroundColor =  backColor.cgColor
            
            let title = pausing ? " 暂停中":" 正在共享"
            self.sLab.stringValue = Td.sh().name+title
        }
    }
    
    
    var topTabs:[TabView] = []
    let sours:[Sour] = [
        Sour.init(title: "静音", imgNom: "toolbar_mute_voip_normal"),
        Sour.init(title: "关闭视频", imgNom: "toolbar_stop_video_normal"),
        Sour.init(title: "更改共享", imgNom: "toolbar_k_share_new"),
        Sour.init(title: "暂停共享", imgNom: "toolbar_k_share_stop"),
        Sour.init(title: "更多", imgNom: "toolbar_k_share_more")
    ]
    
    override func loadView() {
        
        let view = NSView.init(frame: NSRect.init(x: 0, y: 0, width: 520, height: 65+22))//580
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.clear.cgColor
        self.view = view
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        
        //共享需要关闭时候
        NotificationCenter.default.addObserver(self,selector: #selector(sendStream(not:)),name: MTSendStreamNotification,object: nil)
    }
    
    
    convenience init(role:OneRole,source:TRTCScreenCaptureSourceInfo) {
        self.init()
        self.role = role
        self.sourceInfo = source
        self.setupUI()
        self.loadData()
    }
    
    
    func loadData() {
        let size = (self.role == .host) ? NSSize.init(width: self.getWidth(), height: 65+22):NSSize.init(width: 320, height: 22)
        self.view.frame = CGRect.init(origin: CGPoint.zero, size: size)
        
        
        self.topContainer.isHidden = !(self.role == .host)
        let audioImage = Td.sh().lc.isMute ? "toolbar_nomute_voip_normal":"toolbar_mute_voip_normal"
        self.topTabs[safe:0]?.icon.image = NSImage.image(name:audioImage)
        let mutetitle = Td.sh().lc.isMute ? "解除静音":"静音"
        self.topTabs[safe:0]?.title.stringValue = mutetitle
        
        
        let videoImage = Td.sh().lc.isVdOpen ? "toolbar_stop_video_normal":"toolbar_start_video_press"
        self.topTabs[safe:1]?.icon.image = NSImage.image(name:videoImage)
        let vdOpentitle = Td.sh().lc.isVdOpen ? "关闭视频":"开启视频"
        self.topTabs[safe:1]?.title.stringValue = vdOpentitle
    }
    
    func setupUI() {
        self.view.addSubview(topContainer)
        topContainer.snp.makeConstraints { (make) in
            make.top.centerX.width.equalToSuperview()
            make.height.equalTo(self.view.frame.height-22)
        }
        self.topTabs = self.initSub(inView: self.topContainer)
        
        self.view.addSubview(container)
        container.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(topContainer.snp.bottom)
            make.width.equalTo(320)
            make.height.equalTo(22)
        }
        
        container.addSubview(sLab)
        sLab.snp.makeConstraints { (make) in
            make.width.equalTo(240)
            make.height.equalTo(16)
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        container.addSubview(closeButtom)
        closeButtom.snp.makeConstraints { (make) in
            make.left.equalTo(sLab.snp.right)
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
            make.right.equalToSuperview()
        }
        
        container.addSubview(topButtom)
        topButtom.snp.makeConstraints { (make) in
            make.width.height.equalTo(22)
            make.left.equalTo(0)
            make.centerY.equalToSuperview()
        }
        
    }
    lazy var topContainer: GradientView = {
        let view =  GradientView()
        view.wantsLayer = true
        view.layer?.cornerRadius = 10
        view.layer?.masksToBounds = true
        return view
    }()
    
    lazy var contentView: NSView = {
        let view = NSView()
        view.layer?.backgroundColor = color_gray(100).cgColor
        view.wantsLayer = true
        return view
    }()
    
    func getWidth() -> CGFloat {
        return kTabWidth*CGFloat(self.sours.count)+20+20+40
    }
    
    
    func initSub(inView:NSView) -> [TabView] {
        var tabs:[TabView] = []
        for (inx,val) in sours.enumerated() {
            let group = TabGroup.init(image: val.imgNom, title: val.title)
            let view = TabView.init(list: group)
            view.delegate = self
            view.title.textColor = color_gray(200)
            view.tag = 100+inx
            inView.addSubview(view)
            tabs.append(view)
            
            view.snp.makeConstraints { (make) in
                make.height.equalTo(60)
                make.width.equalTo(kTabWidth)
                make.bottom.equalToSuperview()
                if inx == 0 {
                    make.left.equalTo(20)
                }else {
                    make.left.equalTo(tabs[inx-1].snp.right).offset(10)
                }
            }
        }
        return tabs
    }
    
    lazy var topButtom: ZHButton = {
        let btn = ZHButton.init()
        btn.iconImage = NSImage.image(name:"icon_shared_topbuttom")
        btn.backgroundNormalColor = NSColor.clear
        btn.backgroundSelectedColor = NSColor.clear
        btn.backgroundHoverColor = color_gray(255,alpha: 0.3)
        btn.backgroundHighlightColor = color_gray(255,alpha: 0.3)
        btn.alphaValue = 0.6
        btn.target = self
        btn.action = #selector(topButtomAction(sender:))
        return btn
    }()
    
    lazy var container: ZConnerView = {
        let view = ZConnerView.init(bgColor: color_green190, conner: [.topLeft,.topRight], radius: 0)
        view.wantsLayer = true
        view.layer?.backgroundColor = color_green190.cgColor
        return view
    }()
    
    lazy var sLab: NSLabel = {
        let lab = NSLabel.label(title: Td.sh().name+" 正在共享", textColor: color_gray(0), font: NSFont.systemFont(ofSize: 12))
        lab.alignment = .center
        return lab
    }()
    
    lazy var closeButtom: ZHButton = {
        let btn = ZHButton.init()
        btn.zh_title = "停止共享"
        btn.zh_font = NSFont.systemFont(ofSize: 12)
        btn.zh_color = color_gray(255)
        btn.zh_backgroundColor = NSColor.red
        btn.target = self
        btn.action = #selector(closeBtnAction)
        return btn
    }()
    
}

extension TCSdMenuViewController {
    @objc func topButtomAction(sender:ZHButton) {
        self.isExpand = !self.isExpand
    }
    
    @objc func moreBtnAction(sender:NSView)  {
        sender.layoutSubtreeIfNeeded()
        
        let menu = NSMenu.init()
        //menu.isDark = true
        self.createItems().forEach { (item) in
            menu.addItem(item)
        }
        menu.needsUpdate()
        let p = NSPoint(x: 0, y: sender.frame.origin.y+sender.frame.height+14-80)
        self.upMenu = menu
        self.upMenu!.popUp(positioning: nil, at: p, in: sender)
    }
    
    func createItems() -> [ZHMenuItem] {
        var item:[ZHMenuItem] = []
        let cursor = self.hasCursor ? "隐藏捕获鼠标光标":"捕获鼠标光标"
        let hightlight = self.hasHighlight ? "隐藏焦点框":"显示焦点框"
        let pause = self.pausing ? "恢复共享":"暂停共享"
        let menuNames = self.role == .join ? ["---","100% 窗口比例","75% 窗口比例","50% 窗口比例","---","鼠标跟随","并排模式"]:["重启共享",pause,"---","100% 窗口比例","75% 窗口比例","50% 窗口比例","---",hightlight,cursor]
        
         let resuliton = TXLiteManager._resolutionFrom(string: Td.sh().sd.param.videoResolution)
        
        var resulitonIndex:Int = 0
        if self.role == .join {
            if resuliton == ._1280_720  {
                resulitonIndex = 0
             }else if resuliton == ._960_540 {
                resulitonIndex = 1
             }else if resuliton == ._640_480 {
                resulitonIndex = 2
            }
        }else {
            if resuliton == ._1280_720  {
                resulitonIndex = 3
             }else if resuliton == ._960_540 {
                resulitonIndex = 4
             }else if resuliton == ._640_480 {
                resulitonIndex = 5
            }
        }
         
         
        for (inx,val) in menuNames.enumerated() {
            let menu = ZHMenuItem.init(title: val, keyEquivalent: "", saction: { (view) in
                self.selectk(item: view as! ZHMenuItem)
            })
            menu.tag = inx
            menu.target = self
            menu.isEnabled = true
            if inx == resulitonIndex {
                menu.kstate = .on
            }else if inx == 5 && self.role == .join {
                Td.sh().sd.hasSplit = !Td.sh().sd.hasSplit
                menu.kstate = Td.sh().sd.hasSplit ? .on :.off
            }else {
                menu.kstate = .off
            }
            
            item.append(menu)
        }
        return item
    }
    
    @objc func selectk(item:ZHMenuItem) {
        self.upMenu?.cancelTracking()
        if self.role == .join {
            switch item.tag {
            case 0:
                Td.sh().sd.param.videoResolution = "1280x720"
                self.startScreenCapture()
            case 1:
                Td.sh().sd.param.videoResolution = "960x540"
                self.startScreenCapture()
            case 2:
                Td.sh().sd.param.videoResolution = "640x480"
                self.startScreenCapture()
            case 4:
                item.kstate = item.kstate == .on ? .off:.on
                MTNot.postHasSlipe(isok: Td.sh().sd.hasSplit)
            default:
                break
            }
        }else {
            switch item.tag {
            case 0:
                self.resumeScreenCapture()
            case 1:
                self.pauseScreenCapture()
            case 3:
                Td.sh().sd.param.videoResolution = "1280x720"
                self.startScreenCapture()
            case 4:
                Td.sh().sd.param.videoResolution = "960x540"
                self.startScreenCapture()
            case 5:
                Td.sh().sd.param.videoResolution = "640x480"
                self.startScreenCapture()
            case 7:
                self.hasHighlight = !self.hasHighlight
                self.resetScreenCaptureTarget()
            case 8:
                self.hasCursor = !self.hasCursor
                self.resetScreenCaptureTarget()
            default:
                break
            }
        }
        
    }
    
    func resetScreenCaptureTarget() {
        let rect = self.sourceInfo.type == TRTCScreenCaptureSourceType.screen ? NSScreen.main!.frame : CGRect.zero
        TXLiteManager.shared().selectScreenCaptureTarget(screenSource: self.sourceInfo, rect: rect, capturesCursor: self.hasCursor, highlight: self.hasHighlight)
    }
    
    func startScreenCapture() {
        TXLiteManager.shared().stopScreenCapture()
        TXLiteManager.shared().startScreenCapture(nil, param: Td.sh().sd.param)
        self.resetScreenCaptureTarget()
    }
    
    @objc func closeBtnAction() {
        let controller = KlViewController.init(title: "结束共享", massage: "你要结束当前共享吗", buttomTitles: ["确定","取消"], indexBlock: { (index, viewController) in
            if index == 0 {
                self.closeScreenShare()
            }
        }, navBlock: nil)
        let window = NSWindow.init(contentViewController: controller)
        window.makeKeyAndOrderFront(nil)
        
    }
    
    func closeScreenShare() {
        TXLiteManager.shared().stopScreenCapture()
        TrtcEngine.exitScreenShare()
    }
    
    func muteAction() {
        if Td.sh().cloud.isALLMute == false || String.isHostId() {
            Td.sh().lc.isMute = !Td.sh().lc.isMute
            let isMute = Td.sh().lc.isMute
            MTNot.postNotMute(isok: isMute)
            let audioImage = isMute ? "toolbar_nomute_voip_normal":"toolbar_mute_voip_normal"
            self.topTabs[safe:0]?.icon.image = NSImage.image(name:audioImage)
            let title = isMute ? "解除静音":"静音"
            self.topTabs[safe:0]?.title.stringValue = title
            
        }else {
            show_msg("需要主持人解除全体静音")
        }
    }
    
    func videoAction()  {
        if TCGirdRender.shared().current() != nil {
            Td.sh().lc.isVdOpen = !Td.sh().lc.isVdOpen
            let isVdOpen = Td.sh().lc.isVdOpen
            MTNot.postNotVdOpen(isok: isVdOpen)
            let videoImage = isVdOpen ? "toolbar_stop_video_normal":"toolbar_start_video_press"
            self.topTabs[safe:1]?.icon.image = NSImage.image(name:videoImage)
            let title = isVdOpen ? "关闭视频":"开启视频"
            self.topTabs[safe:1]?.title.stringValue = title
        }
    }
    
    func resetScreenCapture() {
        let window = NSWindow.init(contentViewController: TCSdColloctViewController())
        window.lorderFront(nil)
    }
    
    func resumeScreenCapture() {
        TXLiteManager.shared().pauseScreenCapture()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.2) {
            TXLiteManager.shared().resumeScreenCapture()
            self.resetScreenCaptureTarget()
        }
    }
    
    func pauseScreenCapture() {
        self.pausing = !self.pausing
        let videoImage = self.pausing ? "toolbar_k_share_start":"toolbar_k_share_stop"
        let title = self.pausing ? "恢复共享":"暂停共享"
        self.topTabs[safe:3]?.icon.image = NSImage.image(name:videoImage)
        self.topTabs[safe:3]?.title.stringValue = title
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.2) {
            if self.pausing {
                TXLiteManager.shared().pauseScreenCapture()
            }else {
                TXLiteManager.shared().resumeScreenCapture()
            }
            self.resetScreenCaptureTarget()
        }
    }
}

extension TCSdMenuViewController :TabViewDelegate {
    func tabView_rightButtomAction(tab:TabView) {
        
    }
    
    func tabView_mouseDown(event: NSEvent, senber: TabView) {
        switch senber.tag {
        case 100:
            self.muteAction()
        case 101:
            self.videoAction()
        case 102:
            self.resetScreenCapture()
        case 103:
            self.pauseScreenCapture()
        case 104:
            self.moreBtnAction(sender: senber)
        default:
            break
        }
    }
}

extension TCSdMenuViewController {
    @objc func sendStream(not:Notification) {
        if let mode = not.object as? StreamMode {
            if mode.available == false {
                self.closeScreenShare()
            }
        }
    }
}


